import Vue from 'vue'
import Router from 'vue-router'
// import localStore from '@/utils/localstorage'
import Login from '../components/Login'
import NotFund from '../components/404'

Vue.use(Router)

let routes = [
  {
    path: '/',
    component: Login,
    name: 'login'
  },
  {
    path: '/404',
    component: NotFund,
    name: '404'
  },
  // 动态获取路由
  {
    path: '/main',
    component: () => '../layout/layout'
    // redirect: () => {
    //   let path = localStore.fetch_user().redirects.onePath
    //   return {path: path}
    // }
  }
]

const router = new Router({
  routes
})

// 挂载路由导航卫士，用来验证将要访问的页面是否有访问权限 ，即否登录是否有token存在
router.beforeEach((to, from, next) => {
  // to 将要跳转到的页面   from 从哪个路径页面 ，  next 放行函数
  if (to.path === '/') return next() // 登录页直接放行

  let token = sessionStorage.getItem('token')
  console.log('token:' + token)
  if (!token) {
    return next('/') // token 不存在  跳转到登录页面
  }
})

export default router
